// API服务配置
const API_BASE_URL = '/api';

// 创建axios实例
const api = axios.create({
    baseURL: API_BASE_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器
api.interceptors.request.use(
    config => {
        // 可以在这里添加token等认证信息
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
api.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        console.error('API请求失败:', error);
        if (error.response) {
            // 服务器返回错误状态码
            switch (error.response.status) {
                case 401:
                    // 未授权，跳转到登录页
                    window.location.href = '/pages/login.html';
                    break;
                case 403:
                    layui.use('layer', () => {
                        layui.layer.msg('权限不足', {icon: 2});
                    });
                    break;
                case 500:
                    layui.use('layer', () => {
                        layui.layer.msg('服务器内部错误', {icon: 2});
                    });
                    break;
                default:
                    layui.use('layer', () => {
                        layui.layer.msg('请求失败', {icon: 2});
                    });
            }
        } else if (error.request) {
            // 网络错误
            layui.use('layer', () => {
                layui.layer.msg('网络连接失败', {icon: 2});
            });
        }
        return Promise.reject(error);
    }
);

// 仪表板相关API
const dashboardAPI = {
    // 获取仪表板统计数据
    getStats: () => api.get('/dashboard/stats'),
    
    // 获取舆情趋势数据
    getTrendData: (params) => api.get('/dashboard/trend', { params }),
    
    // 获取情感分布数据
    getSentimentData: (params) => api.get('/dashboard/sentiment', { params }),
    
    // 获取最新舆情动态
    getRecentNews: (params) => api.get('/dashboard/recent-news', { params }),
    
    // 获取模型运行状态
    getModelStatus: () => api.get('/dashboard/model-status')
};

// 舆情分析相关API
const opinionAPI = {
    // 获取热词统计
    getHotWords: (params) => api.get('/opinion/hot-words', { params }),
    
    // 获取全平台舆情统计
    getPlatformStats: (params) => api.get('/opinion/platform-stats', { params }),
    
    // 获取文章分析数据
    getArticleAnalysis: (params) => api.get('/opinion/article-analysis', { params }),
    
    // 获取IP分析数据
    getIpAnalysis: (params) => api.get('/opinion/ip-analysis', { params }),
    
    // 获取评论分析数据
    getCommentAnalysis: (params) => api.get('/opinion/comment-analysis', { params }),
    
    // 获取舆情分析报告
    getOpinionReport: (params) => api.get('/opinion/report', { params }),
    
    // 获取词云图数据
    getWordCloud: (params) => api.get('/opinion/word-cloud', { params })
};

// AI模型相关API
const aiModelAPI = {
    // 获取可用模型列表
    getModels: () => api.get('/ai/models'),
    
    // 测试模型连接
    testModel: (modelName) => api.post('/ai/test-model', { modelName }),
    
    // 获取模型配置
    getModelConfig: (modelName) => api.get(`/ai/model-config/${modelName}`),
    
    // 更新模型配置
    updateModelConfig: (modelName, config) => api.put(`/ai/model-config/${modelName}`, config),
    
    // 执行舆情分析
    analyzeOpinion: (data) => api.post('/ai/analyze', data),
    
    // 获取分析历史
    getAnalysisHistory: (params) => api.get('/ai/history', { params })
};

// 系统管理相关API
const systemAPI = {
    // 用户登录
    login: (credentials) => api.post('/auth/login', credentials),
    
    // 用户注册
    register: (userData) => api.post('/auth/register', userData),
    
    // 获取用户信息
    getUserInfo: () => api.get('/user/info'),
    
    // 更新用户信息
    updateUserInfo: (userData) => api.put('/user/info', userData),
    
    // 修改密码
    changePassword: (passwordData) => api.put('/user/password', passwordData),
    
    // 获取系统配置
    getSystemConfig: () => api.get('/system/config'),
    
    // 更新系统配置
    updateSystemConfig: (config) => api.put('/system/config', config)
};

// 数据管理相关API
const dataAPI = {
    // 获取数据源列表
    getDataSources: () => api.get('/data/sources'),
    
    // 添加数据源
    addDataSource: (sourceData) => api.post('/data/sources', sourceData),
    
    // 更新数据源
    updateDataSource: (id, sourceData) => api.put(`/data/sources/${id}`, sourceData),
    
    // 删除数据源
    deleteDataSource: (id) => api.delete(`/data/sources/${id}`),
    
    // 测试数据源连接
    testDataSource: (sourceData) => api.post('/data/test-connection', sourceData),
    
    // 获取数据同步状态
    getSyncStatus: () => api.get('/data/sync-status'),
    
    // 手动触发数据同步
    triggerSync: () => api.post('/data/sync'),
    
    // 获取数据统计
    getDataStats: (params) => api.get('/data/stats', { params })
};

// 导出API对象
window.API = {
    dashboard: dashboardAPI,
    opinion: opinionAPI,
    aiModel: aiModelAPI,
    system: systemAPI,
    data: dataAPI
};

// 工具函数
window.APIUtils = {
    // 格式化日期
    formatDate: (date, format = 'YYYY-MM-DD HH:mm:ss') => {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    },
    
    // 格式化数字
    formatNumber: (num) => {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    },
    
    // 获取时间范围
    getTimeRange: (range) => {
        const now = new Date();
        const start = new Date();
        
        switch (range) {
            case 'today':
                start.setHours(0, 0, 0, 0);
                break;
            case 'week':
                start.setDate(now.getDate() - 7);
                break;
            case 'month':
                start.setMonth(now.getMonth() - 1);
                break;
            case 'year':
                start.setFullYear(now.getFullYear() - 1);
                break;
            default:
                start.setDate(now.getDate() - 7);
        }
        
        return {
            start: start.toISOString(),
            end: now.toISOString()
        };
    },
    
    // 防抖函数
    debounce: (func, wait) => {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // 节流函数
    throttle: (func, limit) => {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
}; 